package com.jianying.day03;

import com.jianying.beans.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * ClassName: Flink09_Trans_Map
 * Package: com.atguigu.day03
 * Description:
 *
 * @Author: tubage
 * @Create: 2024/4/1 15:05
 * @Version: 1.0
 */
public class Flink12_Trans_KeyBy {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> socketDS = env.socketTextStream("localhost", 8888);

        SingleOutputStreamOperator<WaterSensor> mapDS = socketDS.map(
                new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String s) throws Exception {
                        String[] fieldArr = s.split(",");
                        return new WaterSensor(fieldArr[0], Long.valueOf(fieldArr[1]), Integer.valueOf(fieldArr[2]));
                    }
                }
        );

        // 分组流 键控流
        KeyedStream<WaterSensor, String> keyByDS = mapDS.keyBy(waterSensor -> waterSensor.id);

        // 聚合算子，会将中间聚合的结果保存在状态中
        SingleOutputStreamOperator<WaterSensor> sumDS = keyByDS.sum("vc");
        sumDS.print();


        env.execute();
    }
}
